package com.example.cofeed;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Process;
import android.util.Log;
import android.view.Gravity;

import com.ada.common.cache.CacheManager;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import  com.example.cofeed.util.ToastUtils;;
import com.blankj.utilcode.util.Utils;
import com.bolex.autoEx.AutoEx;
import com.example.cofeed.base.BaseApplication;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.even.RefreshEven;
import com.huawei.android.hms.agent.HMSAgent;
import com.iflytek.cloud.SpeechUtility;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.MiPushClient;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import cn.jpush.android.api.JPushInterface;
import okhttp3.OkHttpClient;


public class App extends BaseApplication {

    private long mLastClickBackTime = 0L;
    long nowTime;

    @Override
    protected void init() {

        AppUtils.registerAppStatusChangedListener(this, new Utils.OnAppStatusChangedListener() {
            @Override
            public void onForeground() {//前台
                nowTime = System.currentTimeMillis();

//                if (nowTime - mLastClickBackTime > 1000 * 60 * 6) {
                if (mLastClickBackTime == 0) {
                    return;
                }

//                if (nowTime - mLastClickBackTime > 1000 * 60 * 6) {
                if (nowTime - mLastClickBackTime > 1000 * 6) {
                    //大于两小时
                    if (nowTime - mLastClickBackTime > 1000 * 60 * 60 * 2) {
//                    if (nowTime - mLastClickBackTime > 1000 * 15){
                        AppUtils.relaunchApp();
                    } else {
                        EventBus.getDefault().post(new RefreshEven(0));

                    }

                }
            }

            @Override
            public void onBackground() {
                nowTime = System.currentTimeMillis();

                mLastClickBackTime = nowTime;

            }
        });

        UMConfigure.init(this, " 5c089384b465f5cb8e0003d4", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, null);

        CrashReport.initCrashReport(this, "b22198e486", false);

//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return;
//        }
//        LeakCanary.install(this);

        SpeechUtility.createUtility(this, "appid=" + "5a14f160");

        AutoEx.apply();//一行即可

        CacheManager.init(this);

        //友盟分享
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, "0f9f0607a606d770a0c84efe");
        Utils.init(this);
        ToastUtils.setGravity(Gravity.CENTER, 0, 0);

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //第三方的开源库，使用通知显示当前请求的log，不过在做文件下载的时候，这个库好像有问题，对文件判断不准确
        //builder.addInterceptor(new ChuckInterceptor(this));

        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
//        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));              //使用数据库保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失

        //https相关设置，以下几种方案根据需要自己设置
        //方法一：信任所有证书,不安全有风险
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
//        //配置https的域名匹配规则，详细看demo的初始化介绍，不需要就不要加入，使用不当会导致https握手失败
//        builder.hostnameVerifier(new SafeHostnameVerifier());

        // 其他统一的配置
        // 详细说明看GitHub文档：https://github.com/jeasonlzy/
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
//                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3);                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers);                     //全局公共头
//                .addCommonParams(params);                       //全局公共参数

        String brand = Build.BRAND.toLowerCase();

        switch (brand) {
            case "huawei":
                HMSAgent.init(this);
                break;
            case "xiaomi":
                //初始化push推送服务
                if (shouldInit()) {
                    MiPushClient.registerPush(this, "2882303761517875346", "5961787519346");
                }
                //打开Log
                LoggerInterface newLogger = new LoggerInterface() {

                    @Override
                    public void setTag(String tag) {
                        // ignore
                    }

                    @Override
                    public void log(String content, Throwable t) {
                        Log.d("xiaomi", content, t);
                    }

                    @Override
                    public void log(String content) {
                        Log.d("xiaomi", content);
                    }
                };
                break;

//            case "meizu":
//                if(MzSystemUtils.isBrandMeizu(this)){
//                    PushManager.register(this, "117268", "34db62f1a60243cab2d54076e3869307");
//                }
//                break;
            //vivo
//            case "vivo":
//                PushClient.getInstance(getApplicationContext()).initialize();
//                PushClient.getInstance(getApplicationContext()).turnOnPush(new IPushActionListener() {
//
//                    @Override
//                    public void onStateChanged(int state) {
//                        if (state != 0) {
//                            Log.d("vivo","打开push异常[" + state + "]");
//                            JPushInterface.setDebugMode(true); 	// 设置开启日志,发布时请关闭日志
//                            JPushInterface.init(getApplicationContext());     		// 初始化 JPush
//                            String registrationId = JPushInterface.getRegistrationID(getApplicationContext());
//                            SPUtils.getInstance().put(SputilsConstant.DEVICE_ID, registrationId);
//                        } else {
//                            Log.d("vivo", "打开push成功");
//                        }
//                        ToastUtils.showShort(state + "");
//
//                    }
//                });
//                break;
//                //oppo
//            case "oppo":
//                break;
//                //联想
//            case "lenovo":
//                break;
            default:
                JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
                JPushInterface.init(this);            // 初始化 JPush
                String registrationId = JPushInterface.getRegistrationID(this);
                SPUtils.getInstance().put(SputilsConstant.DEVICE_ID, registrationId);

//                ToastUtils.showShort("极光魅族设备号：" + registrationId);
                break;
        }


    }

    //    //各个平台的配置，建议放在全局Application或者程序入口
    {
        PlatformConfig.setWeixin("wx49675b36ae234f15", "70fc0be4e7986b0f06d50100d7a67df9");

        PlatformConfig.setSinaWeibo("2981811202", "e607db64af68bec51884f3d1f7c69422", "https://m.cofeed.com");
        PlatformConfig.setQQZone("101543630", "faccc9d4e9a6f0ea370678405f54dbf7");

    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }
}
